package xyz.example.securegeyserext

import org.geysermc.geyser.api.extension.Extension
import org.geysermc.event.subscribe.Subscribe
import org.geysermc.geyser.api.event.lifecycle.GeyserPreInitializeEvent
import org.geysermc.geyser.api.event.lifecycle.GeyserPostInitializeEvent
import org.geysermc.geyser.api.event.lifecycle.GeyserDefineCommandsEvent
import org.geysermc.geyser.api.connection.GeyserConnection
import xyz.example.securegeyserext.util.AESCipher
import xyz.example.securegeyserext.command.SecureCommand
import xyz.example.securegeyserext.config.ConfigManager
import java.nio.charset.StandardCharsets
import javax.crypto.SecretKey

class SecureBridgeExt : Extension {

    companion object {
        const val CHANNEL = "secure:bridge"
        lateinit var key: SecretKey
        private lateinit var instance: SecureBridgeExt
        
        fun getInstance(): SecureBridgeExt = instance
    }
    
    private lateinit var configManager: ConfigManager

    @Subscribe
    fun onPreInit(event: GeyserPreInitializeEvent) {
        instance = this
        logger().info("SecureBridgeExt pre-initializing...")
        
        // 初始化配置管理器
        configManager = ConfigManager(dataFolder())
        if (!configManager.load()) {
            logger().error("Failed to load configuration!")
            return
        }
        
        // 从配置文件读取AES密钥
        val keyString = configManager.getString(ConfigManager.AES_KEY, "AAAAAAAAAAAAAAAAAAAAAA==")
        key = AESCipher.readKey(keyString)
        
        logger().info("SecureBridgeExt configuration loaded with secure channel: $CHANNEL")
        if (configManager.getBoolean(ConfigManager.DEBUG)) {
            logger().info("Debug mode enabled")
        }
    }

    @Subscribe
    fun onPostInit(event: GeyserPostInitializeEvent) {
        logger().info("SecureBridgeExt post-initialization complete!")
    }

    @Subscribe
    fun onDefineCommands(event: GeyserDefineCommandsEvent) {
        try {
            val command = SecureCommand.createCommand()
            event.register(command)
            logger().info("SecureBridge command registered successfully")
        } catch (ex: Exception) {
            logger().error("Failed to register SecureBridge command", ex)
        }
    }

    /**
     * 处理加密消息
     */
    fun handleSecureMessage(connection: GeyserConnection, data: ByteArray) {
        try {
            val decrypted = AESCipher.decrypt(key, data)
            val message = String(decrypted, StandardCharsets.UTF_8)
            
            // 发送解密后的消息给玩家
            connection.sendMessage(message)
            logger().info("Secure message sent to ${connection.name()}: $message")
        } catch (ex: Exception) {
            logger().error("Failed to decrypt secure message for ${connection.name()}", ex)
        }
    }

    /**
     * 加密并发送消息
     */
    fun sendSecureMessage(connection: GeyserConnection, message: String) {
        try {
            // 检查消息长度
            val maxLength = configManager.getInt(ConfigManager.MAX_MESSAGE_LENGTH, 512)
            if (message.length > maxLength) {
                connection.sendMessage("Message too long! Maximum length is $maxLength characters.")
                return
            }
            
            val messageBytes = message.toByteArray(StandardCharsets.UTF_8)
            val encrypted = AESCipher.encrypt(key, messageBytes)
            
            // 通过插件消息通道发送加密数据
            // 注意：在新版API中，可能需要不同的方法来发送插件消息
            // connection.sendPluginMessage(CHANNEL, encrypted)
            
            if (configManager.getBoolean(ConfigManager.DEBUG)) {
                logger().info("Encrypted message prepared for ${connection.name()}: $message")
            } else {
                logger().info("Encrypted message prepared for ${connection.name()}")
            }
        } catch (ex: Exception) {
            logger().error("Failed to prepare secure message for ${connection.name()}", ex)
        }
    }

    /**
     * 获取配置管理器
     */
    fun getConfigManager(): ConfigManager = configManager
}
